﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Courier.Core;
using Contour.Addons.CourierSupport.ItemProviders.Entities;

namespace Contour.Addons.CourierSupport.ItemProviders
{
    public class FormItemProvider : ItemProvider
    {
        public FormItemProvider()
        {
            this.Name = "Forms";
            this.Description = "Extracts contour forms, accepts a form guid as a valid identifier";
            this.Id = ProviderIDCollection.formItemProviderGuid;
            this.ExtractionDirectory = "forms";
            this.Index = 20;
            this.ProviderIcon = umbraco.IO.SystemDirectories.Umbraco + "/images/umbraco/icon_form.gif";
        }

        public override List<SystemItem> AvailableSystemItems()
        {
            List<SystemItem> items = new List<SystemItem>();

            Umbraco.Forms.Data.Storage.FormStorage fs = new Umbraco.Forms.Data.Storage.FormStorage();

            foreach (var f in fs.GetAllForms())
            {
                SystemItem item = new SystemItem();
                item.ItemId = new ItemIdentifier(f.Id.ToString(), this.Id);
                item.Name = f.Name;
                item.Description = f.Name + "Form";
                item.Icon = "icon_form.gif";
                item.HasChildren = false;
                items.Add(item);
            }
            return items;
        }

        public override Item HandleDeserialize(ItemIdentifier id, byte[] item)
        {
            return Umbraco.Courier.Core.Serialization.Serializer.Deserialize<Form>(item);
        }

        public override Item HandleExtract(Item item)
        {
            Form f = (Form)item;
            f = this.DatabasePersistence.PersistItem<Form>(f);
            return f;
        }

        public override Item HandlePack(ItemIdentifier id)
        {
            Form item = this.DatabasePersistence.RetrieveItem<Form>(id);

            if (item == null)
                return null;


            return item;
        }

        public static ItemProvider Instance()
        {
            return Umbraco.Courier.Core.ProviderModel.ItemProviderCollection.Instance.GetProvider(ProviderIDCollection.formItemProviderGuid);
        }
    }

}